/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BLL;

import DAL.ConnectData;
import DTO.Cart;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mrson
 */
public class BCart {
    ConnectData condata;
    
    public BCart(){
        condata = new ConnectData();
    }
    
    public ArrayList<Cart> getAll(String query){
        
            ArrayList<Cart> carts = new ArrayList<Cart>();
            Cart cart = null;
            try {
            ResultSet rs = condata.executeQuery(query);
            while(rs.next()){
                cart = new Cart();
                cart.setCartId(rs.getInt("cartId"));
                cart.setNumber(rs.getInt("number"));
                cart.setProductId(rs.getInt("productId"));
                cart.setUserId(rs.getInt("userId"));
                carts.add(cart);
            }
            this.condata.close();
       } catch (Exception ex) {
            System.out.print(ex.toString());
        }
        return carts.isEmpty()?null:carts;
    }
    
    public ArrayList<Cart> getAll(){
        String sql = "select * from tblCart";
        return this.getAll(sql);
    }
    
    public Cart getById(int cartId){
        String sql = "select * from thlCart where cartId="+cartId;
        ArrayList<Cart> carts = this.getAll(sql);
        return carts==null?null:carts.get(0);
    }
    
    public ArrayList<Cart> getByUserId(int userId)
    {
        String sql = "select * from tblCart where userId = "+userId;
        return this.getAll(sql);
    }
    
 
    
    public boolean insert(Cart cart){
        
            boolean check = false;
            int rs = -1;
           String sql = "insert into tblCart (userId, productId) values ("+cart.getUserId()+","+cart.getProductId()+")";
            try {
            rs = condata.executeUpdate(sql);
            if(rs>0){
                check = true;
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(BCart.class.getName()).log(Level.SEVERE, null, ex);
        }
        return check;
    }
    
    public boolean delete(int cartId){
        
            boolean check = false;
            int rs = -1;
           String sql = "delete from tblCart where cartid = " + cartId;
            try {
            rs = condata.executeUpdate(sql);
            if(rs>0){
                check = true;
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(BCart.class.getName()).log(Level.SEVERE, null, ex);
        }
        return check;
    }
    
}
